package com.pxxy.yuyi.inter;

;


import com.pxxy.yuyi.entity.Admin;
import com.pxxy.yuyi.service.AdminService;
import com.pxxy.yuyi.utils.ConstUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutoInterHandler implements HandlerInterceptor {

    @Autowired
    private AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie数组，遍历后，取出用户名和密码
        System.out.println("--进入自动登录拦截器--");
        String username=null;
        String password=null;
        Cookie[] cookies = request.getCookies();
        System.out.println("111"+cookies);
        if (cookies!=null){
            for (Cookie cookie : cookies){
                if (cookie.getName().equals(ConstUtils.AUTO_LOGIN)){
                    username = cookie.getValue().split(":")[0];
                    password = cookie.getValue().split(":")[1];
                    System.out.println("cookie--"+username+"and"+password);
                    break;
                }
            }
        }
        //根据用户名和密码进行登录，反馈对象不为空，说明用户名和密码没问题
        if(username!=null&&password!=null){
           Admin admin= adminService.selectLogin(username,password);
            if (admin!=null){
                request.getSession().setAttribute(ConstUtils.LOGIN_USER,admin);
                response.sendRedirect(request.getContextPath()+"/admin/show");
            }

        }
        return true;
    }






}
